package com.example.cipherdemo.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;

public class AESUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);

    public static void main(String[] args) {

        String name="fadfdfadfasdf打的费";
        String encodeRule=genEncodeRule();
        String enResult=AESEncrypt(name,encodeRule);
        System.out.println(enResult);
        String deResult=AESDecrypt(enResult,encodeRule);
        System.out.println(deResult);

        }


    /**
     * 获取AES编码规则
     *
     * @return
     */
    public static String genEncodeRule() {
        StringBuilder chars = new StringBuilder("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 16; i++) {
            int num = Integer.parseInt(String.valueOf(Math.round(Math.floor(Math.random() * chars.length()))));
            result.append(chars.charAt(num));
        }
        return result.toString();
    }

    /**
     * AES加密
     * @param content
     * @param encodeRule
     * @return
     */
    public static String AESEncrypt(String content, String encodeRule) {
        try {
            byte[] bytes = encodeRule.getBytes("UTF-8");
            SecretKeySpec keySpec = new SecretKeySpec(bytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] bytes1 = cipher.doFinal(content.getBytes("UTF-8"));
            String result = Base64.getEncoder().encodeToString(bytes1);
            return result;

        } catch (Exception e) {
            LOGGER.error("AES编码异常", e);
        }
        return null;
    }

    public static String AESDecrypt(String content,String encodeRule){
        byte[] decode = Base64.getDecoder().decode(content);
        try {
            SecretKeySpec keySpec=new SecretKeySpec(encodeRule.getBytes("UTF-8"),"AES");
            Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE,keySpec);
            byte[] bytes = cipher.doFinal(decode);
            return new String(bytes,"UTF-8");
        } catch (Exception e) {
            LOGGER.error("AES解码异常",e);
        }
        return null;
    }


}
